package com.wudizaba.pg.service.impl;




import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wudizaba.pg.domain.DTO.StoredProcedureDrillDTO;
import com.wudizaba.pg.domain.IndexObject;
import com.wudizaba.pg.domain.QUery.PageQuery;
import com.wudizaba.pg.domain.po.StoredProcedureDrill;
import com.wudizaba.pg.domain.po.veryGoodFriends;
import com.wudizaba.pg.mapper.StoredProcedureDrillMapper;
import com.wudizaba.pg.service.IStoredProcedureDrillService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author k
 * @since 2024-05-02
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class StoredProcedureDrillServiceImpl extends ServiceImpl<StoredProcedureDrillMapper, StoredProcedureDrill> implements IStoredProcedureDrillService {

    private final StoredProcedureDrillMapper storedProcedureDrillMapper;

    /**
     * 新增数据
     *
     * @param id 主键
     * @return 新增成功
     */
    @Override
    public String saveStoredProcedureDrill(Integer id) {
        StoredProcedureDrill storedProcedureDrill = createStoredProcedureDrill();
        log.info("存储过程参数 {}", storedProcedureDrill);
        // 调用存储过程->新增数据
        storedProcedureDrillMapper.saveStoredProcedureDrill(storedProcedureDrill);
        return "新增成功";
    }


    /**
     * 更新数据
     *
     * @return 更新成功
     */
    @Override
    public String updateStoredProcedureDrill(StoredProcedureDrillDTO storedProcedureDrill) {
        log.info("存储过程参数 {}", storedProcedureDrill);
        StoredProcedureDrill storedProcedureDrill1 = BeanUtil.copyProperties(storedProcedureDrill, StoredProcedureDrill.class);
        storedProcedureDrillMapper.updateStoredProcedureDrill(storedProcedureDrill1);
        return "更新成功";
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除成功
     */
    @Override
    public String deleteStoredProcedureDrill(Integer id) {
        log.info("存储过程参数 {}", id);
        storedProcedureDrillMapper.deleteStoredProcedureDrill(id);
        return "删除成功";
    }

    /**
     * '
     * 查询数据
     *
     * @param pageQuery 分页参数
     * @return 查询成功
     */
    @Override
    public List<StoredProcedureDrill> getStoredProcedureDrill(PageQuery pageQuery) {
        int page = pageQuery.getPage();
        int size = pageQuery.getSize();

        log.info("存储过程参数 {},{}", size, page);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("page_num", page);
        resultMap.put("page_size", size);
        List<StoredProcedureDrill> storedProcedureDrills = new ArrayList<>();
        // 调用存储过程->查询数据
        String string = storedProcedureDrillMapper.getStoredProcedureDrill(resultMap);
        log.info("存储过程调用结果 {}", string);

        //将字符串转换成List
        List<StoredProcedureDrill> storedProcedureDrillList = parseStringTOList(string);
        //调用函数
        // List<String> stringList =  storedProcedureDrillMapper.getStoredProcedureDrillFunction(resultMap);
        // log.info("函数调用结果 {}", stringList);
        //  storedProcedureDrills = getStoredProcedureDrillFunction(stringList);

        return storedProcedureDrillList;
    }

    /**
     * 封装结果
     * 将字符串转换成List
     *
     * @param string 字符串
     * @return
     */
    public List<StoredProcedureDrill> parseStringTOList(String string) {
        ArrayList<StoredProcedureDrill> storedProcedureDrills = new ArrayList<>();
        //分割字符串
        String[] storedProcedureDrillStr = string.split("\",\"");
        // 字符串去除指定字符串{"

        storedProcedureDrillStr[0] = storedProcedureDrillStr[0].replace("{\"", "");
        storedProcedureDrillStr[storedProcedureDrillStr.length - 1] = storedProcedureDrillStr[storedProcedureDrillStr.length - 1].replace("\"}", "");
        for (String sp : storedProcedureDrillStr) {
            //将每条数据封装成StoredProcedureDrill对象
            //去除字符串首尾的括号
            String s1 = sp.substring(1, sp.length() - 1);
            System.out.println("每个练习生对象 = " + s1);
            String[] strings = s1.split(",");
            for (int i1 = 0; i1 < strings.length; i1++) {
                System.out.println("每个属性：" + strings[i1]);
                StoredProcedureDrill storedProcedureDrill = new StoredProcedureDrill();
                storedProcedureDrill.setId(Integer.parseInt(strings[0]));
                storedProcedureDrill.setName(strings[1]);
                storedProcedureDrill.setAge(Integer.parseInt(strings[2]));
                storedProcedureDrill.setExerciseDuration(strings[3]);
                storedProcedureDrill.setHobbies(strings[4]);
                storedProcedureDrill.setBirthYear(LocalDate.parse(strings[5]));
                storedProcedureDrill.setJob(strings[6]);

                //封装数组
                List<Integer> arrayList = new ArrayList<>();
                //string[7]截取{之后
                int index1 = strings[7].indexOf('{');
                String s7 = strings[7].substring(index1 + 1);
                arrayList.add(Integer.valueOf(s7));
                //数组最后一位
                IndexObject stringIndex1 = getStringIndex(strings, "}", 1);
                String string1 = strings[stringIndex1.getIndex()];
                int index = string1.indexOf('}');
                String s7e = string1.substring(0, index);
                for (int i = 7 + 1; i < stringIndex1.getIndex(); i++) {
                    arrayList.add(Integer.valueOf(strings[i]));
                }
                arrayList.add(Integer.valueOf(s7e));
                Integer[] integers = arrayList.toArray(new Integer[0]);
                storedProcedureDrill.setPurses(integers);
                System.out.println("arrayList = " + arrayList);

                //对象
                int i = stringIndex1.getIndex() + 1;
                String stringObj = strings[i];
                System.out.println("stringObj = " + stringObj);
                IndexObject stringIndex = getStringIndex(strings, "(", 1);
                IndexObject stringIndexOne = getStringIndex(strings, ")", 1);
                Integer index3 = stringIndex.getIndex();
                Integer index4 = stringIndexOne.getIndex();
                log.info("index3 = " + strings[index3]);
                log.info("index4 = " + strings[index4]);
                int in1 = strings[index3].indexOf("(");
                String newString1 = strings[index3].substring(in1 + 1);
                int in2 = strings[index4].indexOf(")");
                String newString2 = strings[index4].substring(0, in2);

                veryGoodFriends veryGoodFriends = new veryGoodFriends(newString1, Short.parseShort(newString2));
                storedProcedureDrill.setVeryGoodFriends(veryGoodFriends);
                //日期刷子
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String dateTimesave1 = strings[index4 + 1];
                String dateTimesave2 = strings[index4 + 2];
                //去除前后双引号
                dateTimesave1 = dateTimesave1.substring(1, dateTimesave1.length() - 1);
                dateTimesave2 = dateTimesave2.substring(1, dateTimesave2.length() - 1);
                //去除毫秒


                int j = dateTimesave1.indexOf('.');
                dateTimesave1 = dateTimesave1.substring(1, j);
                dateTimesave2 = dateTimesave2.substring(1, j);
                System.out.println("dateTimesave2 = " + dateTimesave1);
                System.out.println("dateTimesave2 = " + dateTimesave2);

                LocalDateTime dateTimesave = LocalDateTime.parse(dateTimesave1, formatter);
                LocalDateTime dateTimeupadte = LocalDateTime.parse(dateTimesave2, formatter);
                System.out.println("dateTimesave = " + dateTimesave);
                System.out.println("dateTimeupadte = " + dateTimeupadte);
                storedProcedureDrill.setCreateTime(dateTimesave);
                storedProcedureDrill.setUpdateTime(dateTimeupadte);
                log.info("函数调用结果 {}", storedProcedureDrill);
                storedProcedureDrills.add(storedProcedureDrill);
            }

        }
        return storedProcedureDrills;
    }
    /**
     * 创建对象
     */
    public StoredProcedureDrill createStoredProcedureDrill() {
        Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        StoredProcedureDrill storedProcedureDrill = new StoredProcedureDrill();
        storedProcedureDrill.setName("test");
        storedProcedureDrill.setAge(18);
        storedProcedureDrill.setExerciseDuration("两年半");
        storedProcedureDrill.setHobbies("唱、跳、RAP、篮球");
        storedProcedureDrill.setBirthYear(createRandomDate());
        storedProcedureDrill.setJob("无业");
        storedProcedureDrill.setPurses(array);
        storedProcedureDrill.setVeryGoodFriends(new veryGoodFriends("妮基肽酶", (short) 20));
        storedProcedureDrill.setCreateTime(createRandomTime());
        storedProcedureDrill.setUpdateTime(createRandomTime());

        return storedProcedureDrill;
    }

    /**
     * 获取字符串出现的位置
     */
    public IndexObject getStringIndex(String[] strings, String sub,int index){
        int count = 0;
        int secondIndex = -1;

        for (int i = 0; i < strings.length; i++) {
            log.info("字符串 {}", strings[i]);
            if (strings[i].contains(sub)) {
                count++;
                if (count == index) {
                    secondIndex = i;
                    break;  // 已经找到第N次出现的位置，可以结束循环
                }
            }
            log.info("==============================");

        }
        IndexObject indexObject = new IndexObject();
        indexObject.setIndex(secondIndex);
        return indexObject;
    }
    /**
     * 封装pgsql函数返回的结果
     */
    public List<StoredProcedureDrill> getStoredProcedureDrillFunction (List < String > stringList) {
        ArrayList<StoredProcedureDrill> storedProcedureDrills = new ArrayList<>();
        for (String s : stringList) {
            log.info("函数调用结果 {}", s);
            //将每条数据封装成StoredProcedureDrill对象
            //去除字符串首尾的括号
            String s1 = s.substring(1, s.length() - 1);
            String[] strings = s1.split(",");

            StoredProcedureDrill storedProcedureDrill = new StoredProcedureDrill();
            storedProcedureDrill.setId(Integer.parseInt(strings[0]));
            storedProcedureDrill.setName(strings[1]);
            storedProcedureDrill.setAge(Integer.parseInt(strings[2]));
            storedProcedureDrill.setExerciseDuration(strings[3]);
            storedProcedureDrill.setHobbies(strings[4]);
            storedProcedureDrill.setBirthYear(LocalDate.parse(strings[5]));
            storedProcedureDrill.setJob(strings[6]);
            // 截取strings[7]之后的字符串
            int indexF = 7;
            IndexObject IndexL = getStringIndex(strings, "}", 1);
            Integer index2 = IndexL.getIndex();

            List<Integer> arrayList = new ArrayList<>();
            int i1 = strings[7].indexOf('{');
            String s7 = strings[7].substring(i1 + 1);
            arrayList.add(Integer.parseInt(s7));
            for (int i = indexF + 1; i < index2; i++) {
                String arrayString = strings[i];
                arrayList.add(Integer.parseInt(arrayString));
            }
            String[] split = strings[index2].split("}");
            arrayList.add(Integer.parseInt(split[0]));
            //集合转数组
            Integer[] arrays = arrayList.toArray(new Integer[0]);
            storedProcedureDrill.setPurses(arrays);

            IndexObject stringIndex = getStringIndex(strings, "(", 1);
            IndexObject stringIndex1 = getStringIndex(strings, ")", 1);
            Integer index3 = stringIndex.getIndex();
            Integer index4 = stringIndex1.getIndex();
            log.info("index3 = " + strings[index3]);
            log.info("index4 = " + strings[index4]);
            int in1 = strings[index3].indexOf("(");
            String newString1 = strings[index3].substring(in1 + 1);
            int in2 = strings[index4].indexOf(")");
            String newString2 = strings[index4].substring(0, in2);

            veryGoodFriends veryGoodFriends = new veryGoodFriends(newString1, Short.parseShort(newString2));
            storedProcedureDrill.setVeryGoodFriends(veryGoodFriends);
            //日期刷子
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String dateTimesave1 = strings[index4 + 1];
            String dateTimesave2 = strings[index4 + 2];
            //去除前后双引号
            dateTimesave1 = dateTimesave1.substring(1, dateTimesave1.length() - 1);
            dateTimesave2 = dateTimesave2.substring(1, dateTimesave2.length() - 1);
            //去除毫秒


            int i = dateTimesave1.indexOf('.');
            dateTimesave1 = dateTimesave1.substring(0, i);
            dateTimesave2 = dateTimesave2.substring(0, i);
            // System.out.println("dateTimesave2 = " + dateTimesave1);
            // System.out.println("dateTimesave2 = " + dateTimesave2);
            LocalDateTime dateTimesave = LocalDateTime.parse(dateTimesave1, formatter);
            LocalDateTime dateTimeupadte = LocalDateTime.parse(dateTimesave2, formatter);
            System.out.println("dateTimesave = " + dateTimesave);
            System.out.println("dateTimeupadte = " + dateTimeupadte);
            storedProcedureDrill.setCreateTime(dateTimesave);
            storedProcedureDrill.setUpdateTime(dateTimeupadte);
            log.info("函数调用结果 {}", storedProcedureDrill);
            storedProcedureDrills.add(storedProcedureDrill);
        }
        return storedProcedureDrills;
    }

    /**
     * 创建随机日期
     */
    private LocalDate createRandomDate () {
        // 创建 Random 对象
        Random random = new Random();

        // 生成随机的年份（范围：1900 到 2024）
        int year = random.nextInt(125) + 1900;

        // 生成随机的月份（范围：1 到 12）
        int month = random.nextInt(12) + 1;

        // 生成随机的日期（范围：1 到 当月的最大天数）
        int day = random.nextInt(LocalDate.of(year, month, 1).lengthOfMonth()) + 1;

        // 使用 of() 方法创建 LocalDate 对象
        LocalDate randomDate = LocalDate.of(year, month, day);
        log.info("随机日期 {}", randomDate);
        return randomDate;
    }

    /**
     * 创建随机时间
     */
    public LocalDateTime createRandomTime() {
        // 获取当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        log.info("当前时间 {}", currentDateTime);
        // 随机生成年份、月份、日期、小时、分钟和秒
        Random random = new Random();
        int year = random.nextInt(50) + 1970; // 生成 1970 到 2019 年之间的随机年份
        int month = random.nextInt(12) + 1; // 生成 1 到 12 之间的随机月份
        int day = random.nextInt(28) + 1; // 生成 1 到 28 之间的随机日期（假设为一个月的最大天数）
        int hour = random.nextInt(24); // 生成 0 到 23 之间的随机小时
        int minute = random.nextInt(60); // 生成 0 到 59 之间的随机分钟
        int second = random.nextInt(60); // 生成 0 到 59 之间的随机秒数

        // 使用随机生成的年、月、日、时、分、秒创建 LocalDateTime 对象
        LocalDateTime randomDateTime = LocalDateTime.of(year, month, day, hour, minute, second);

        log.info("随机时间 {}", randomDateTime);
        return randomDateTime;
    }
}
